<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Region extends MY_Controller {

    /**
     * @var ConsumerAddressModel
     */
    public $mAddress = null;
    /**
     * @var AdmSettingModel
     */
    public $mSett = null;

	public function __construct(){
		parent::__construct();
		$this->loadModel('ConsumerAddressModel', 'mAddress', 'consumer');
        $this->loadModel('AdmSettingModel', 'mSett', 'admin');
	}
	
	/**
	 * 首页
	 */
	public function index(){
	    $this->db->select('province,city,county,latitude,longitude')
            ->where(array('is_default' => 2));
        $list = $this->mAddress->getAll($this->mAddress->tbAddress);


        $data = array('data' => array());
        if (!empty($list)) {
            foreach ($list as $k => $v) {
                $data['data'][] = array($v['longitude'], $v['latitude'], 1);
            }
        }
        $data = array(
            'data' => json_encode($data),
            'list' => $list,
            'title' => '人数统计',
            'ak' => $this->mSett->get('map_key','deliveryman')
        );
		$this->view('statistics/region', $data, 'datatable,date_range_picker,e_chart');
	}

    /**
     * 获取列表
     */
    public function getList(){
        $this->db->select('county,count(id) as total')
            ->where(array('is_default' => 2))
            ->group_by('county');
        $data = $this->mAddress->pagination($this->mAddress->tbAddress);
        $ids = array();
        if (!empty($data['data'])) {
            foreach ($data['data'] as $v) {
                if (!in_array($v['county'], $ids)){
                    $ids[] = $v['county'];
                }
            }
            $c = $this->mSett->getLocationNameByIds($ids);
            foreach ($data['data'] as $k => $vv) {
                $data['aaData'][$k][] = isset($c[$vv['county']]) ? $c[$vv['county']]['name'] : '';
                $total = adminCreateBtn(array(
                    'label' => $vv['total'].'人',
                    'attr' => array(
                        'href' => getUrl('member/consumer?county='.$vv['county']),
                        'class' => 'deco blue',
                        'target' => "_blank"
                    ),
                    'tag' => 'a',
                    'permissions' => array(
                        'module' => 'member',
                        'key' => 'consumer-view'
                    )
                ));
                $data['aaData'][$k][] = empty($total) ? $vv['total'].'人' : $total;
            }
        }
        unset($data['data']);
        echo json_encode($data);

    }
}
